package net.jxtz.jxtzos.authentication;


import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.jxtz.jxtzos.entity.auth.User;
import net.jxtz.jxtzos.entity.auth.Wechat;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * jwt令牌工具
 *
 * @author a123
 */
public final class JwtUtils {

    public static final String TOKEN_HEAD = "Authorization";

    public static final String TOKEN_PREFIX = "Bearer ";

    public static final String SECRET = "ae7cf117b24a7012873767d706ebb6fd4f09ebb6fd4fab47764d20607";

    public static final String TOKEN_PARAM_PREFIX = "_jwt";

    /**
     * 签发人
     */
    private static final String ISSUER = "lmh";

    private JwtUtils(){}

    /**
     * 创建jwt
     *
     * @param userName 用户名
     * @param userDetails 用户信息封装对象
     * @return jwt字符串
     */
    public static String create(String userName, UserDetails userDetails) {
        Map<String, Object> map = new HashMap<>();
        map.put("userName", userDetails.getUsername());
        map.put("authorities",userDetails.getAuthorities());
        return Jwts.builder()
                // 初始化claims
                .setClaims(map)
                .setSubject(userName)
                .setIssuedAt(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()))
                .setIssuer(ISSUER)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 获取jwt 的 Subject（主题）
     * @param jwt jwt
     * @return 解析对象
     */
    public static String subject(String jwt){
        return claims(jwt).getSubject();
    }

    /**
     * 解析用户信息
     * @param jwt jwt
     * @return MyUserDetails
     */
    public static MyUserDetails userDetails(String jwt) {
        return JSON.parseObject(JSON.toJSONString(claims(jwt)), MyUserDetails.class);
    }

    /**
     * 解析用户信息
     * @param jwt jwt
     * @return wechatUserInfo
     */
    public static Wechat wechatUserInfo(String jwt){
        return JSON.parseObject(JSON.toJSONString(claims(jwt)), Wechat.class);
    }


    private static Claims claims(String jwt) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
